<template>
    <div id="app">
        <div class="box">
            <div>
                <template v-if="$Power.PowerSelect(userPower, currentPagePower)">
                    <el-input class="l-input" v-model="search.keyWords" placeholder="关键字搜索"></el-input>
                    <el-button type="primary" class="l-margin-l15" v-on:click="getList">查询</el-button>
                </template>

                <el-button v-if="$Power.PowerAdd(userPower, currentPagePower)" type="success" v-on:click="onAdd"> 新增角色</el-button>
            </div>
        </div>
        <div class="box">
            <el-table :data="list" border :height="`calc(100vh - 305px)`" :highlight-current-row="true">
                <el-table-column label="角色名称" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.roleName }}
                    </template>
                </el-table-column>
                <el-table-column label="描述" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.remark }}
                    </template>
                </el-table-column>

                <el-table-column label="操作" width="280" fixed="right" align="center">
                    <template slot-scope="scope">
                        <el-button type="primary" size="mini" v-if="$Power.PowerUpdate(userPower, currentPagePower)" plain v-on:click="onEditPower(scope.row)">设置权限</el-button>
                        <el-button type="primary" size="mini" v-if="$Power.PowerUpdate(userPower, currentPagePower)" plain v-on:click="onEdit(scope.row)">编辑</el-button>
                        <el-button type="danger" size="mini" v-if="$Power.PowerDelete(userPower, currentPagePower)" plain v-on:click="onDelete(scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </div>
        <div style="height: 10px">&nbsp;</div>
        <div class="box">
            <el-pagination
                v-on:size-change="handleSizeChange"
                v-on:current-change="handleCurrentChange"
                v-bind:current-page="currentPage"
                v-bind:page-sizes="[10, 20, 30, 40]"
                v-bind:page-size="pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                v-if="reflushPageFlag"
                v-bind:total="total"
            >
            </el-pagination>
        </div>
        <!--对话框-->
        <el-dialog :title="EditTitle" :close-on-click-modal="false" :visible.sync="dialogVisible" width="30%" custom-class="l-dialog">
            <div class="l-div-400">
                <el-form ref="form" :model="form" label-width="130px">
                    <el-row>
                        <el-col :span="24">
                            <el-form-item label="角色名称">
                                <el-input v-model="form.roleName" class="l-input-form" placeholder="角色名称"></el-input>
                            </el-form-item>
                            <el-form-item label="描述">
                                <el-input v-model="form.remark" class="l-input-form" placeholder="描述"> </el-input>
                            </el-form-item>
                            <el-form-item label="排序">
                                <el-input v-model="form.sort" class="l-input-form" placeholder="排序"> </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button v-on:click="dialogVisible = false">取 消</el-button>
                <el-button type="primary" v-on:click="onSave">确 定</el-button>
            </span>
        </el-dialog>

        <!--设置菜单权限-->
        <el-dialog title="设置菜单权限" :close-on-click-modal="false" :visible.sync="dialogVisibleMenuPower" width="80%" custom-class="l-dialog">
            <div class="l-div-400">
                <el-checkbox v-model="selectAll" v-on:change="onChange()">全选</el-checkbox>

                <el-divider></el-divider>

                <div class="l-power">
                    <div v-for="(item, index1) in menuListV1" :key="index1">
                        <el-row class="l-menurow" :i="index1">
                            <label class="l-menu-title">{{ item.menuName }}</label>
                            <el-checkbox v-model="item.checked" v-on:change="onChangeV1(item.id)">全选</el-checkbox>
                        </el-row>
                        <div v-for="(itemNode, index2) in menuListV2" :key="index2">
                            <div v-if="itemNode.parentId == item.id">
                                <el-row class="l-menurow l-m-80" :gutter="20">
                                    <label class="l-menu-title2">{{ itemNode.menuName }}</label>
                                    <el-checkbox v-model="itemNode.checked" v-on:change="onChangeV2(itemNode.id)">全选 </el-checkbox>
                                    <el-divider direction="vertical"></el-divider>
                                    <div style="display: inline-block" v-for="(itemCheck, index3) in itemNode.data" :key="index2">
                                        <el-checkbox style="margin-left: 5px" v-model="itemCheck.isCheck" v-on:change="onChangeV3(itemNode.id)">
                                            {{ itemCheck.name }}
                                        </el-checkbox>
                                    </div>
                                    <!-- <el-checkbox v-model="itemNode.checkedSelect" v-on:change="onChangeV3(itemNode.id)">查询
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedAdd" v-on:change="onChangeV3(itemNode.id)">新增
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedDelete" v-on:change="onChangeV3(itemNode.id)">删除
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedUpdate" v-on:change="onChangeV3(itemNode.id)">修改
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedExport" v-on:change="onChangeV3(itemNode.id)">导出
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedEnable" v-on:change="onChangeV3(itemNode.id)">启用禁用
                                    </el-checkbox>
                                    <el-checkbox v-model="itemNode.checkedAction" v-on:change="onChangeV3(itemNode.id)">
                                        管理员操作</el-checkbox> -->
                                </el-row>
                            </div>
                        </div>

                        <el-divider></el-divider>
                    </div>
                </div>
            </div>
            <span slot="footer" class="dialog-footer">
                <el-button v-on:click="dialogVisibleMenuPower = false">取 消</el-button>
                <el-button type="primary" v-on:click="onSavePower">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import { GetRoleList, DeleteRole, GetMenuPowerList, SaveRole, SaveRolePowerV3, GetRolePower } from "@/service/systemapi";
export default {
    data() {
        return {
            userPower: "",
            currentPagePower: "",
            search: {
                keyWords: ""
            },
            //分页 开始
            currentPage: 1,
            pagesize: 10,
            total: 0,
            reflushPageFlag: true,
            //分页 结束
            isAdd: true,
            list: [],
            dialogVisible: false,
            EditTitle: "",
            form: {
                id: "",
                roleName: "",
                sort: 1,
                remark: ""
            },

            //权限
            dialogVisibleMenuPower: false,
            menuList: [],
            menuListV1: [],
            menuListV2: [],
            currentRoleId: "",
            selectAll: false, //全选
            powerList: []
        };
    },
    created() {
        this.currentPagePower = this.$route.query.name;
        this.userPower = localStorage.getItem("userPower");
        this.InitData();
    },
    watch: {},
    methods: {
        //初始化
        InitData() {
            if (this.$Power.PowerSelect(this.userPower, this.currentPagePower)) {
                this.getList();
            }
        },
        //查询列表
        getList() {
            this.openLoading();
            this.list = [];
            var that = this;

            let jsondata = {
                PageIndex: this.currentPage,
                PageSize: this.pagesize,
                keyWords: this.search.keyWords
            };
            GetRoleList(jsondata)
                .then(res => {
                    if (res.data != undefined) {
                        that.list = res.data.list;
                        that.total = res.data.total;

                        that.$nextTick(function () {
                            that.reflushPageFlag = true;
                        });
                    }
                    that.closeLoading();
                })
                .catch(err => {
                    this.$message.error("数据请求异常");
                    that.closeLoading();
                });
        },

        //初始化表单
        initForm() {
            this.form.id = "";
            this.form.roleName = "";
            this.form.remark = "";
            this.form.sort = 1;
        },
        onAdd() {
            this.initForm();

            if (this.list != null && this.list.length > 0) {
                let currentList = this.list.sort(function (a, b) {
                    return b.sort - a.sort;
                })[0];
                this.form.sort = currentList.sort + 1;

                //重新排序一下 这是个小bug
                this.list.sort(function (a, b) {
                    return a.sort - b.sort;
                });
            }

            this.isAdd = true;
            this.dialogVisible = true;
            this.EditTitle = "新增";
        },
        onEdit(row) {
            this.initForm();
            this.isAdd = false;
            this.dialogVisible = true;
            this.EditTitle = "修改";

            //赋值
            this.form.id = row.id;
            this.form.roleName = row.roleName;
            this.form.remark = row.remark;
            this.form.sort = row.sort;
        },
        //编辑角色权限
        onEditPower(row) {
            console.log("row", row);
            this.currentRoleId = row.id;
            this.initForm();
            this.dialogVisibleMenuPower = true;

            this.getMenus(row.id).then(res => {
                this.getRolePowerList();
            });
        },
        onDelete(row) {
            var that = this;
            this.$confirm("是否删除?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning"
            }).then(() => {
                that.openLoading();
                DeleteRole(row.id)
                    .then(res => {
                        that.closeLoading();
                        console.log(res);
                        if (res.success) {
                            that.getList();
                            that.$message({ message: "删除成功", type: "success" });
                        } else {
                            that.$message.error(res.msg);
                        }
                    })
                    .catch(err => {
                        that.$message.error("删除失败");
                        that.closeLoading();
                    });
            });
        },
        onSave() {
            var that = this;
            that.openLoading();

            SaveRole(this.form)
                .then(res => {
                    console.log(res);
                    that.closeLoading();
                    if (res.success) {
                        that.$message({ message: "操作成功", type: "success" });
                        that.getList();
                        that.dialogVisible = false;
                    } else {
                        that.$message.error(res.msg);
                    }
                })
                .catch(err => {
                    that.$message.error("操作失败");
                    that.closeLoading();
                });
        },
        //全选
        onChange() {
            let currentCheckAll = this.selectAll;
            this.menuListV1.forEach(item => {
                item.checked = currentCheckAll;
            });
            this.menuListV2.forEach(item => {
                item.checked = currentCheckAll;
                for (let index = 0; index < item.data.length; index++) {
                    item.data[index].isCheck = currentCheckAll;
                }
            });
            this.onFlashData();
        },
        //一级菜单
        onChangeV1(id) {
            console.log(id);

            var that = this;

            //获取到当前菜单
            let currentMenuV1 = that.menuListV1.filter(item => {
                return item.id == id;
            })[0];

            //循环二级菜单
            that.menuListV2.forEach(item => {
                if (item.parentId == id) {
                    item.checked = currentMenuV1.checked;
                    for (let index = 0; index < item.data.length; index++) {
                        item.data[index].isCheck = currentMenuV1.checked;
                    }
                }
            });

            //循环一级菜单
            let j = 0;
            that.menuListV1.forEach(item => {
                if (item.checked == currentMenuV1.checked) {
                    j++;
                }
            });
            if (j == that.menuListV1.length) {
                that.selectAll = currentMenuV1.checked;
            } else {
                that.selectAll = false;
            }

            this.onFlashData();
        },
        //二级菜单
        onChangeV2(id) {
            console.log("二级", id);

            //查找当前二级菜单
            var that = this;

            that.menuListV2.forEach(item => {
                if (item.id == id) {
                    for (let index = 0; index < item.data.length; index++) {
                        item.data[index].isCheck = item.checked;
                    }

                    if (item.checked == false) {
                        that.selectAll = false;

                        //上级去掉
                        that.menuListV1.forEach(ell => {
                            if (ell.id == item.parentId) {
                                ell.checked = false;
                            }
                        });
                    } else {
                        that.funMenuSelectAction2(id);
                    }
                }
            });
            this.onFlashData();
        },
        onChangeV3(id) {
            console.log(id);
            console.log(this.menuListV2);
            var that = this;
            that.menuListV2.forEach(item => {
                if (item.id == id) {
                    var SelectV3 = item.data.filter(res => {
                        return res.isCheck == false;
                    });

                    if (SelectV3 == 0) {
                        item.checked = true;
                        that.funMenuSelectAction2(id);
                    } else {
                        //去除上级所有全选按钮
                        item.checked = false;
                        that.selectAll = false;

                        //上级去掉
                        that.menuListV1.forEach(ell => {
                            if (ell.id == item.parentId) {
                                ell.checked = false;
                            }
                        });
                    }
                }
            });
            this.onFlashData();
        },
        funMenuSelectAction2(id) {
            var that = this;
            //查询当前二级菜单 一级菜单
            let currentV1Id = this.menuListV2.filter(a => {
                return a.id == id;
            })[0].parentId;

            let count1 = this.menuListV2.filter(a => {
                return a.parentId == currentV1Id;
            }).length;
            let count2 = this.menuListV2.filter(a => {
                return a.parentId == currentV1Id && a.checked == true;
            }).length;
            if (count1 == count2) {
                that.menuListV1.forEach(item => {
                    if (item.id == currentV1Id) {
                        item.checked = true;
                        that.funMenuSelectAction();
                    }
                });
            }
        },
        //查询 一级 是否全部选中
        funMenuSelectAction() {
            let tempCount = this.menuListV1.length;

            let tempCount2 = this.menuListV1.filter(item => {
                return item.checked;
            }).length;

            this.selectAll = tempCount == tempCount2;
        },
        //刷新数据
        onFlashData() {
            var that = this;
            if (this.menuListV1 != undefined && this.menuListV1 != null && this.menuListV1.length > 0) {
                for (let i = 0; i < this.menuListV1.length; i++) {
                    let temp = this.menuListV1[i];
                    that.$set(that.menuListV1, i, temp);
                }
            }
            if (this.menuListV2 != undefined && this.menuListV2 != null && this.menuListV2.length > 0) {
                for (let i = 0; i < this.menuListV2.length; i++) {
                    let temp = this.menuListV2[i];
                    that.$set(that.menuListV2, i, temp);
                    for (let index = 0; index < that.menuListV2[i].data.length; index++) {
                        let tempV3 = that.menuListV2[i].data[index];
                        that.$set(that.menuListV2[i].data, index, tempV3);
                    }
                }
            }
        },
        //权限
        getRolePowerList() {
            this.powerList = [];
            var that = this;

            GetRolePower(this.currentRoleId)
                .then(res => {
                    that.powerList = res.data;
                    //设置权限
                    that.SetPower();
                })
                .catch(err => {
                    this.$message.error("数据请求异常");
                });
        },
        //赋值权限
        SetPower() {
            var that = this;
            that.selectAll = false;
            if (that.powerList != undefined && that.powerList.length > 0) {
                let q = 0;
                //循环一级菜单
                for (let i = 0; i < that.menuListV1.length; i++) {
                    //获取当前一级菜单下二级菜单得到数量
                    let tempMenuV2Count = that.menuListV2.filter(item => {
                        return item.parentId == that.menuListV1[i].id;
                    }).length;

                    let p = 0;
                    //循环二级菜单
                    for (let j = 0; j < that.menuListV2.length; j++) {
                        //当前二级菜单 是属于当前一级菜单
                        if (that.menuListV2[j].parentId == that.menuListV1[i].id) {
                            let m = 0;

                            var V3Select = that.menuListV2[j].data.filter(res => {
                                return res.isCheck == false;
                            });

                            if (V3Select.length == 0) {
                                that.menuListV2[j].checked = true;
                                p++;
                            }
                        }
                    }

                    if (p == tempMenuV2Count) {
                        that.menuListV1[i].checked = true;

                        q++;
                    }
                }

                if (q == that.menuListV1.length) {
                    that.selectAll = true;
                }
            } else {
                for (let i = 0; i < that.menuListV1.length; i++) {
                    that.menuListV1[i].checked = false;
                }
                for (let i = 0; i < that.menuListV2.length; i++) {
                    that.menuListV2[i].checked = false;
                }
                that.selectAll = false;
            }
            this.onFlashData();
        },
        //保存权限
        onSavePower() {
            var dataJson = [];

            //循环一级菜单
            var that = this;

            that.menuListV1.forEach(item => {
                if (item.checked) {
                    dataJson.push({
                        MenuId: item.id,
                        MenuActionId: "",
                        PermissionId: ""
                    });
                }
            });

            that.menuListV2.forEach(item => {
                for (let index = 0; index < item.data.length; index++) {
                    if (item.data[index].isCheck) {
                        dataJson.push({
                            MenuId: item.id,
                            MenuActionId: item.data[index].code,
                            PermissionId: item.data[index].id
                        });
                    }
                }
            });

            that.openLoading();
            SaveRolePowerV3({
                RoleId: this.currentRoleId,
                PowerList: dataJson
            })
                .then(res => {
                    console.log(res);
                    that.closeLoading();
                    if (res.success) {
                        that.$message({ message: res.data, type: "success" });
                        that.dialogVisibleMenuPower = false;
                    } else {
                        that.$message.error(res.msg);
                    }
                })
                .catch(err => {
                    that.$message.error("操作失败");
                    that.closeLoading();
                });
        },
        //获取菜单列表
        getMenus(roleId) {
            return new Promise((ok, fail) => {
                this.menuList = [];
                this.menuListV1 = [];
                this.menuListV2 = [];
                var that = this;
                GetMenuPowerList(roleId)
                    .then(res => {
                        if (res.success) {
                            that.menuList = res.data;
                            that.menuListV1 = res.data.filter(item => {
                                return item.level == 1;
                            });
                            that.menuListV2 = res.data.filter(item => {
                                return item.level == 2;
                            });
                            ok("");
                        } else {
                            this.$message.error(res.msg);
                        }
                    })
                    .catch(err => {
                        this.$message.error("系统异常");
                        fail("");
                        console.log(err);
                    });
            });
        },
        //当前条
        handleSizeChange(val) {
            this.pagesize = val;
            this.getList();
        },
        //当前页
        handleCurrentChange(val) {
            this.currentPage = val;
            this.getList();
        }
    }
};
</script>

<style scoped>
.l-input {
    display: inline-block;
    width: 260px;
}

.l-input-form {
    display: inline-block;
    width: 220px;
}

.l-margin-l15 {
    margin-left: 15px;
}

.l-red {
    color: red;
}

.l-menurow {
    margin-bottom: 30px;
}

.l-menu-title {
    font-weight: bold;
    color: green;
    margin-right: 20px;
}

.l-menu-title2 {
    font-weight: bold;
    color: #a95c4b;
    margin-right: 20px;
}

.l-m-80 {
    padding-left: 80px;
}

.l-power {
    height: calc(100vh - 490px);
    overflow-y: scroll;
    padding: 10px;
}
</style>
